<?php

defined('IN_XLP') || exit('Access Denied');

class addressModel extends model {

	function __construct() {
		parent::__construct();
		$this->dbTable = 'address';
	}

	/**
	 * 添加收货地址
	 * @param Int 用户id
	 * @param Array $addr 地址信息数组
	 * @return int 插入数据主键
	 */
	public function add($uid, $addr) {

		// name tel zip province city county detail
		if (!$addr['tel'] OR ! $uid) {
			showError('地址参数不完整');
		}

		$addr['uid'] = $uid;
		$addr['last_use'] = TIME;
		return $this->insert($addr);
	}

	/**
	 * 编辑收货地址
	 * @param  int 	 $id   地址id
	 * @param  array $addr 地址参数
	 * @return int   影响行数
	 */
	public function edit($id, $addr) {

		$uid = user::$userInfo['uid'];

		// name tel zip province city county detail
		if (!$addr['tel'] OR ! $uid OR ! $id) {
			showError('地址参数不完整');
		}

		$addr['last_use'] = TIME;
		return $this->update($addr, array('id' => $id));
	}

	/*
	 * 默认地址信息
	 */
	public function info($uid) {
		$result = M('address')
				->where(array('uid'=>$uid))
				->order('`last_use` desc')
				->find();

		return $result;
	}

	/*
	 * 全部地址信息
	 */
	public function infoAll($uid) {
		$result = M('address')
				->where(array('uid'=>$uid))
				->order('`last_use` desc')
				->findAll();

		return $result;   
	}


	public function getAddrById($id) {
		$result = M('address')
				->where(array('uid'=>user::$userInfo['uid'], 'id'=>$id))
				->find();
		return $result;
	}

	public function getAddrOption($selected=0, $code=0) {
		$addr = M('city')->field('`codeid`,`name`')->where(array('parentid'=>$code))->findAll();

        $options = '';
		foreach ($addr as $v) {
            $select = '';
            if($selected == $v['codeid']) $select = 'selected';
            $options .= "<option value='{$v['codeid']}' $select>{$v['name']}</option>";
        }

        return $options;
	}
}